package com.rizzo.shell.plugins;

import com.rizzo.infrastructure.redis.serializer.RedisKeySerializer;
import com.rizzo.shell.intern.args.RedisTransferArguments;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.logging.Logger;

@Configuration
public class RedisConfig {

    private static Logger logger = Logger.getLogger("com.rizzo.shell.plugins.RedisConfig");

    @Resource(name = "redisArgs")
    private HashMap<RedisTransferArguments, String> args;

    public
    @Bean(name = "redisConnectionFactory")
    JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(args.get(RedisTransferArguments.HOST));
        jedisConnectionFactory.setPort(Integer.parseInt(args.get(RedisTransferArguments.PORT)));
        String password = args.get(RedisTransferArguments.PASSWORD);
        if (StringUtils.hasText(password)) {
            jedisConnectionFactory.setPassword(password);
        }
        jedisConnectionFactory.setUsePool(true);
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxActive(5);
        poolConfig.setMaxIdle(5);
        poolConfig.setMaxWait(2);
        poolConfig.setTestOnBorrow(true);
        jedisConnectionFactory.setPoolConfig(poolConfig);
        return jedisConnectionFactory;
    }

    public
    @Bean(name = "stringRedisTemplate")
    StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }

    public
    @Bean(name = "redisKeyTemplate")
    RedisTemplate redisTemplate() {
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        redisTemplate.setKeySerializer(new RedisKeySerializer());
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}
